package com.qyy.www_chatroom.controller;

import com.qyy.www_chatroom.mapper.UserMapper;
import com.qyy.www_chatroom.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserMapper userMapper;

    @RequestMapping("/login")
    public Object login(String username, String password, HttpServletRequest request){
        //1.先去数据库查username能不能找到对象。
        //如果能找到，看密码是否匹配，如果匹配登录成功，创建会话
        User user = userMapper.selectByName(username);
        if(user == null || !user.getPassword().equals(password)){
            System.out.println("登录失败！，用户名或者密码错误"+user);
            return  new User();
        }
        //2.如果匹配成功，则登录成功，创建会话，我们需要HttpServletRequest来创建会话
        HttpSession session = request.getSession(true);
        session.setAttribute("user",user);
        //避免返回密码
        user.setPassword("");
        return user;
    }

    @RequestMapping("/register")
    public Object register(String username, String password){
        User user = null;
        try {
            user = new User();
            user.setUsername(username);
            user.setPassword(password);
            int ret = userMapper.insert(user);
            System.out.println("注册" + ret);
            user.setPassword("");
        }catch (DuplicateKeyException e){
            System.out.println("注册失败！username=" + username);
            user = new User();
        }
        return user;
    }

    @RequestMapping("userInfo")
    public Object getUserInfo(HttpServletRequest request){
        //1.先从请求中获取会话
        HttpSession session = request.getSession(false);
        if(session == null){
            //用户没登录，返回空对象
            System.out.println("获取不到session对象！");
            return new User();
        }
        //2.从会话中获取到之前保存的用户对象
        User user = (User)session.getAttribute("user");
        if(user == null){
            System.out.println("获取不到 User 对象！");
            return new User();
        }
        user.setPassword("");
        return user;
    }

}
